import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:xunlongchi/util/app_util.dart';

///时间管理
class TimeMag {
  DateTime nowTime = DateTime.now();

  TimeMag({
    this.nowTime,
  });

  TimeMag copyWith({
    DateTime nowTime,
  }) =>
      TimeMag(
        nowTime: nowTime ?? this.nowTime,
      );
}

///时间状态管理
class TimeBloc extends Cubit<TimeMag> {
  Timer _timer;

  TimeBloc({TimeMag state}) : super(TimeMag(nowTime: DateTime.now()));

  ///开始计时
  void start() {
    if (_timer == null || !_timer.isActive) {
      _timer = Timer.periodic(const Duration(milliseconds: 500), (_) {
        ///每秒刷新一次
        emit(state.copyWith(nowTime: DateTime.now()));
      });
    }

    XL.log('时钟设置成功');
  }

  ///结束计时
  void stop() {
    _timer?.cancel();
  }
}
